package learning.directory.Work.数组.Ac;/**
 * Created by Administrator on 2021/2/25.
 */

import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * @date 2021/2/25
 */
public class MoreThanHalfTheNumberDay6 {
    public static void main(String[] args) {
        int[]  array = {1,2,2,2,9,2,4,2,4};
        System.out.println(moreThanHalfNumSolution(array));
    }

    /**
     * 借助hashmap存储数组中每个数出现的次数，最后看是否有数字出现次数超过数组长度的一半
     * @param array
     * @return int
     */
    public static int moreThanHalfNumSolution(int[] array){
        int length = array.length;
        Map<Integer,Integer> map = new HashMap<>();
        for (int value : array) {
            if (!map.containsKey(value)) {
                map.put(value, 1);
            } else {
                map.put(value, map.get(value) + 1);
            }
        }
        for(Map.Entry<Integer,Integer> entry : map.entrySet()){
            if(entry.getValue()*2>length){
                return entry.getKey();
            }
        }
        return  0;
    }
}
